package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.old.Result;
import com.cardbaobao.cardbabyclient.ui.activity.base.SwipeBackActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CreditDetailNewAdapter;
import com.cardbaobao.cardbabyclient.callback.ScrollViewListener;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.widget.CardDetailViewNew;
import com.cardbaobao.cardbabyclient.callback.ICityInfoCallback;
import com.cardbaobao.cardbabyclient.callback.OnLocationListener;
import com.cardbaobao.cardbabyclient.model.City;
import com.cardbaobao.cardbabyclient.model.CreditDetail;
import com.cardbaobao.cardbabyclient.model.CreditDetailSeries;
import com.cardbaobao.cardbabyclient.model.MyLocation;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.MyListView;
import com.cardbaobao.cardbabyclient.widget.ObservableScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnItemClick;
import rx.Observable;
import rx.Subscriber;

/**
 * 信用卡详情页 4.0
 * Created by FHW
 * 2016/06/28
 */
public class CreditDetailActivity extends SwipeBackActivity implements View.OnClickListener, OnLocationListener {
    public static final String CARD_ID_S="cardID";
    public static final String CARD_NAME_S="cardName";
    public static final String SERIES_CARD_ID_S ="seriesCardId";
    public static final String FROM_PAGE_S="fromPage";
    private static final int CODE_LOGIN=100;//登录code
    /**详情容器*/
    @BindView(R.id.id_ll_detail_container)
    View mViewDetailContainer;
    /**详情列表*/
    @BindView(R.id.id_lv_detail)
    MyListView mLvDetail;
    /**卡特权、属性模块布局*/
    private View mViewCardAttribute;
    /**卡详情顶部模块布局*/
    private View mViewCard;
    /**卡详情布局控件集合*/
    private CardDetailViewNew mViewCardDetail = new CardDetailViewNew();
    /**信用卡详情列表适配器*/
    private CreditDetailNewAdapter mDetailAdapter;
    /**
     * 同系列卡和猜你喜欢数据列表
     */
    private List<CreditDetailSeries> mCreditSeriesAndLikeList;
    /**猜你喜欢换一批部分*/
    private List<CreditDetailSeries> mCreditLikeSwitchList;
    /**信用卡ID*/
    private String mCardID;
    /**同系列卡id*/
    private String mSeriesCardId;
    /**信用卡名称*/
    private String mCardName;
    /** 来到信用卡详情的页面（用于大数据埋点）*/
    private String mFromPage;
    /** 是否已点赞*/
    private boolean isCollected;

    @BindView(R.id.id_iv_card_logo)
    ImageView id_iv_card_logo;
    @BindView(R.id.ll_back_white)
    LinearLayout ll_back_white;
    @BindView(R.id.rl_title_white)
    RelativeLayout rl_title_white;
    @BindView(R.id.iv_collect)
    ImageView iv_collect;
    @BindView(R.id.iv_detail_news)
    ImageView iv_detail_news;

    @BindView(R.id.tv_title_white)
    TextView tv_title_white;
    @BindView(R.id.tv_apply)
    TextView tv_apply;

    @BindView(R.id.sv_scroll)
    ObservableScrollView sv_scroll;
    @BindView(R.id.rl_top)
    RelativeLayout rl_top;

    //进办卡通道时必须要传的值，在此处强制获取到[禁止定位权限后，需要手动选择一个城市]
    private String cityId;//城市id
    private String cityName;//城市名称

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_credit_card_detail_page;

        mCardName = getIntent().getStringExtra(CARD_NAME_S);
        tv_title_white.setText(mCardName);
        initInflater();
        //设置父列表
        mViewCardDetail.setListView(mLvDetail);
        //顶部模块
        mViewCard = mInflater.inflate(R.layout.layout_credit_detail_card_top, null);
        mViewCard.setVisibility(View.GONE);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_card_name);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_credit_limit);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_withdraw_limit);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_free_time);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_apply_num);
        mViewCardDetail.addViewById(mViewCard, R.id.id_tv_org_name);
        //特权
        mViewCardAttribute = mInflater.inflate(R.layout.layout_credit_detail_attribute, null);
        mViewCardAttribute.setVisibility(View.GONE);
        mViewCardDetail.addViewById(mViewCardAttribute, R.id.id_ll_Feature_container);//设置卡特点容器
        mViewCardDetail.addViewById(mViewCardAttribute, R.id.id_fly_PrivilegesList);//设置卡特权属性容器
        //添加头部
        mLvDetail.addHeaderView(mViewCard);
        mLvDetail.addHeaderView(mViewCardAttribute);

        ll_back_white.setOnClickListener(this);
        iv_collect.setOnClickListener(this);
        iv_detail_news.setOnClickListener(this);
        tv_apply.setOnClickListener(this);
        rl_title_white.getBackground().mutate().setAlpha(0);

        sv_scroll.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(int x, int y, int oldx, int oldy) {
                final int top = rl_top.getHeight() - rl_title_white.getHeight();
                if (y <= top) {
                    float alpha = ((float) Math.abs(y) / top);
                    rl_title_white.getBackground().mutate().setAlpha((int) (alpha * 255));
                }
            }
        });

    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        mCardID = intent.getStringExtra(CARD_ID_S);
        mSeriesCardId = intent.getStringExtra(SERIES_CARD_ID_S);
        mFromPage = intent.getStringExtra(FROM_PAGE_S);
        loadCreditCardDetail();
        //销毁前面的详情页
//        mApplication.finishActivity();
        LocationUtil.startLocation(mContext, this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credit_detail_opt;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Map<String, String> map = new HashMap<>();
        map.put("id", mCardID);
        map.put("name", mCardName);
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x008), map);
        GoogleAnalyticsUtil.setScreenName(Google.CREDIT_DETAIL);
    }

    private void loadCreditCardDetail(){
        showProgressDialog(false);
        Observable<String> observable;
        if(mApplication.getIsLogin()){
            observable= Api.getCreditCardDetail(mCardID,String.valueOf(mApplication.getUser().getID()));
        }else{
            observable=Api.getCreditCardDetail(mCardID,"0");
        }
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                setCreditDetailTopData(JsonUtil.getData(s, CreditDetail.class));
            }
        });
    }

    private void loadYouLikeData(String cardId,String cityId){
        Observable<String> observable=Api.getYouLikeCreditCards(cardId,cityId);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                setCreditDetailYouLikeListData(JsonUtil.getDataListsByMsg(s,CreditDetailSeries.class));
            }
        });
    }

    /**
     * 收藏
     */
    protected void addCollect(String productId) {
        if (mApplication.getIsLogin() && mApplication.getUser() != null) {
            Observable<String> observable=
                    Api.collect(String.valueOf(mApplication.getUser().getID()),productId,"ZCC0101");
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    Result result = JsonUtil.getResult(s, Result.class);
                    if(result !=null&& Result.SUCCESS.equals(result.getResult())){
                        //收藏成功
                        ToastUtil.showToastOnScreenCenter("收藏成功");
                        iv_collect.setImageResource(R.mipmap.icon_collected);
                        isCollected = true;
                    }else{
                        //收藏失败
                        ToastUtil.showToastOnScreenCenter("收藏失败");
                    }
                }
            });
        } else {
            ToastUtil.showToast("未登录无法收藏");
        }
    }

    /**
     * 取消收藏
     */
    protected void cancelCollect(String productId) {
        if (mApplication.getIsLogin() && mApplication.getUser() != null) {
            Observable<String> observable=
                    Api.unCollect(String.valueOf(mApplication.getUser().getID()),productId,"ZCC0101");
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    Result result = JsonUtil.getResult(s, Result.class);
                    if(result !=null&& Result.SUCCESS.equals(result.getResult())){
                        //取消收藏成功
                        ToastUtil.showToastOnScreenCenter("取消收藏");
                        iv_collect.setImageResource(R.mipmap.icon_collect);
                        isCollected = false;
                    }else{
                        //取消收藏失败
                        ToastUtil.showToastOnScreenCenter("操作失败");
                    }
                }
            });
        } else {
            ToastUtil.showToast("未登录无法收藏");
        }
    }

    /**
     * 设置信用卡详情顶部模块数据
     */
    private void setCreditDetailTopData(CreditDetail mCreditDetail) {
        if (mCreditDetail != null) {
            //顶部详情(除卡片介绍)
            mViewCardDetail.setCreditDetailTopData(mCreditDetail);
            //设置详情收藏状态
            if (!TextUtils.isEmpty(mCreditDetail.getMfID())) {
                if (mApplication.getIsLogin()) {
                    iv_collect.setImageResource(R.mipmap.icon_collected);
                    isCollected = true;
                }
            }
            ImageLoaderUtil.displayImageWithPlaceHolder(
                    URLUtil.CBB_IMG_URL + mCreditDetail.getImage(),
                    id_iv_card_logo,
                    R.drawable.icon_default_credit,
                    DensityUtil.dp2px(6)
            );
        }
        mViewDetailContainer.setVisibility(View.VISIBLE);
        mViewCard.setVisibility(View.VISIBLE);
        mLvDetail.setAdapter(mDetailAdapter);
    }

    /**
     * 设置信用卡详情猜你喜欢列表模块数据
     */
    private void setCreditDetailYouLikeListData(List<CreditDetailSeries> creditDetailSeriesList) {
        SelfUtils.buriedClickData(Self.Action.app_click_credit_card_for_another_patch,
                Self.Action.app_click_credit_card_for_another_patch_des,
                mEnterPageTime,
                mCurrentPageId,
                mPrePageId);
        if (mCreditSeriesAndLikeList == null) mCreditSeriesAndLikeList = new ArrayList<>();
        if (mCreditLikeSwitchList == null) mCreditLikeSwitchList = new ArrayList<>();
        if (creditDetailSeriesList != null && creditDetailSeriesList.size() > 0) {
            int len = creditDetailSeriesList.size();
            if (len > 6) {
                len = 6;//只取六条数据
            }
            for (int i = 0; i < len; i++) {
                CreditDetailSeries credit = creditDetailSeriesList.get(i);
                credit.setTypeId(2);
                credit.setTypeName("猜你喜欢");
                if (i < 3) {
                    mCreditSeriesAndLikeList.add(credit);
                } else {
                    mCreditLikeSwitchList.add(credit);//换一批显示此内容
                }
            }
            if (mDetailAdapter == null) {
                mDetailAdapter = new CreditDetailNewAdapter(mContext, mCreditSeriesAndLikeList, mCreditLikeSwitchList);
            } else {
                mDetailAdapter.setDataSource(mCreditSeriesAndLikeList, mCreditLikeSwitchList);
            }
            mLvDetail.setAdapter(mDetailAdapter);
        }
    }

    /**
     * 同系列，猜你喜欢列表单击事件
     */
    @OnItemClick(R.id.id_lv_detail)
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            SelfUtils.buriedClickData(Self.Action.app_click_credit_card_item,
                    Self.Action.app_click_credit_card_item_des,
                    mEnterPageTime,
                    mCurrentPageId,
                    mPrePageId);
            CreditDetailSeries creditDetailSeries = (CreditDetailSeries) parent.getAdapter().getItem(position);
            if (creditDetailSeries != null) {
                initIntent();
                mIntent.setClass(mContext, CreditDetailActivity.class);
                mIntent.putExtra(CARD_ID_S, creditDetailSeries.getID() + "");
                mIntent.putExtra(SERIES_CARD_ID_S, creditDetailSeries.getSeriesCard());
                mIntent.putExtra(CARD_NAME_S, creditDetailSeries.getName());
                mIntent.putExtra("fromCreditSearch", getIntent().getBooleanExtra("fromCreditSearch", false));
                mIntent.putExtra(FROM_PAGE_S, mCardName + "-猜你喜欢");
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                mContext.startActivity(mIntent);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_LOGIN:
                    startApplyCreditCard();
                    break;
                case CitySelectActivity.REQUEST_CODE:
                    this.cityId = data.getStringExtra(CitySelectActivity.RESULT_CITY_ID_KEY);
                    this.cityName = data.getStringExtra(CitySelectActivity.RESULT_CITY_NAME_KEY);
                    ApplyCreditCard();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back_white:
                finish();
                break;
            case R.id.iv_collect:
                //收藏
                if (isCollected) {
                    //已收藏
                    cancelCollect(mCardID);
                    SelfUtils.buriedClickData(Self.Action.app_click_cancel_collect_credit_card,
                            Self.Action.app_click_cancel_collect_credit_card_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_COLLECT);
                } else {
                    //未收藏
                    addCollect(mCardID);
                    SelfUtils.buriedClickData(Self.Action.app_click_collect_credit_card,
                            Self.Action.app_click_collect_credit_card_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_COLLECT_CAN);
                }
                break;
            case R.id.iv_detail_news:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_credit_card_intro,
                        Self.Action.app_click_credit_card_intro_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                        URLUtil.CREDIT_CARD_INTRO+ "?id=" + mCardID);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, mCardName);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 0);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                mContext.startActivity(mIntent);
                break;
            case R.id.tv_apply:
                //立即申请
                preStartApplyCreditCard();
                break;
        }
    }

    private void preStartApplyCreditCard(){
        if(mApplication.getIsLogin()){
            startApplyCreditCard();
        }else{
            Intent intent=new Intent(mContext,AccountLoginActivity.class);
            intent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    Constant.PLY010201);
            startActivityForResult(intent,CODE_LOGIN);
            overridePendingTransition(R.anim.activity_in_bottom, R.anim.activity_out_top);
        }
    }

    /**
     * 进入申请通道，申请信用卡
     */
    private void startApplyCreditCard() {
        if (!TextUtils.isEmpty(cityId) && !TextUtils.isEmpty(cityName)) {
            ApplyCreditCard();
        } else {
            ToastUtil.showToast("请选择当前所在城市");
            Intent intent = new Intent(mContext, CitySelectActivity.class);
            startActivityForResult(intent, CitySelectActivity.REQUEST_CODE);
        }
    }

    private void ApplyCreditCard() {
        SelfUtils.buriedClickData(Self.Action.app_click_apply_credit_card,
                Self.Action.app_click_apply_credit_card_des,
                mEnterPageTime,
                mCurrentPageId,
                mPrePageId);
//        mApplication.setActivity(this);
        Map<String, String> map = new HashMap<>();
        map.put("fromPage", mFromPage);
        map.put("card_id", mCardID);
        map.put("card_name", mCardName);
        UmengEventUtils.applyCardEvent(mContext, map);
        mController.detailPageApplyCreditCard(mCardID, mCardName, cityId, cityName, mFromPage);
    }

    @Override
    public void locationResult(MyLocation location, int resultCode) {
        switch (resultCode) {
            case LocationUtil.LOCATION_SUCCESS_CODE:
                //定位成功
                cityName = location.getCityName();
                LocationUtil.getProvinceCityIDByCityName(new ICityInfoCallback() {
                    @Override
                    public void onCityInfoResponse(City city) {
                        if (city != null) {
                            cityId = city.getID();
                            loadYouLikeData(mCardID,cityId);
                        }
                    }
                }, cityName);
                break;
            default:
                loadYouLikeData(mCardID,LocationUtil.getCityID());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
